package com.zhongshengnetwork.rightbe.lang.view;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
//import android.support.annotation.NonNull;
//import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
//import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DateUtil;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.banner.BannerView;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.common.pulluprefresh.xlistview.XListView;
import com.zhongshengnetwork.rightbe.dbmodel.NotifydbModel;
import com.zhongshengnetwork.rightbe.dbservice.NotifydbService;
import com.zhongshengnetwork.rightbe.gsonmodel.BannerModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DryCommentModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.ThirdDataNameModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangCommentActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangDetailActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.ThirdLangActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.view.controller.CommonItemViewController;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * Created by luojingxing on 2018/9/7.
 */

public class CommentFragment extends BaseAnalyticsFragment {
    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isHasMore = false;
    private ListView listview;
    //加载动画
    private AVLoadingIndicatorView avi;

    public int type = 0;
    public String userid = null;
    public boolean isNeedLogin = false;

    private Button login_button;

    private List<DryCommentModel> list;
    private List<String> moreList;
    private MyAdapter adapter;
    private View rootView;//缓存Fragment view
    private ImageView no_data_img;

    //轮播推荐
    private float density = 0.0f;
    private int screenWidth = 0;
    private List<View> viewList;
    private List<BannerModel> bannerList;
    BannerView bannerView = null;

    private ClipboardManager myClipboard;
    private RefreshLayout mRefreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.comment_fragment_layout, container, false);
            int width = ScreenUtils.getScreenWidth(getActivity());
            density = ScreenUtils.getScreenDensity(getActivity());
            screenWidth = width;
            if (viewList == null){
                viewList = new ArrayList<View>();
            }
            if (bannerList == null){
                bannerList = new ArrayList<>();
            }
            avi = (AVLoadingIndicatorView)rootView.findViewById(R.id.avi);
            no_data_img = (ImageView)rootView.findViewById(R.id.no_data_img);
            login_button = (Button) rootView.findViewById(R.id.login_button);
            login_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (CommonUtils.isLogin()==false){
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    }else {
                        getData();
                    }
                }
            });
            myClipboard = (ClipboardManager)CustomApplication.mContext.getSystemService(CLIPBOARD_SERVICE);
            if (moreList == null){
                moreList = new ArrayList<String>();
            }
            if (list == null){
                list = new ArrayList<DryCommentModel>();
            }
            listview=(ListView) rootView.findViewById(R.id.comment_listview);
            adapter=new MyAdapter();
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (list == null || list.size() == 0){
                        return;
                    }
                    int index = position;// - 1;
                    if (type == 2){
                        //推荐评论
                        index = position-1;// - 2;
                    }
                    while (index < 0){//解决部分手机点击第一条不是从1开始的问题
                        index+=1;
                    }
                    commentMore(index);
                }
            });

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(true);//启用刷新
            mRefreshLayout.setEnableLoadMore(true);//启用加载
            //刷新
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    //refreshlayout.finishRefresh();
                    getData();
                }
            });
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    //refreshLayout.finishLoadMore();
                    loadMore();
                }
            });
            getData();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
            getData();
        }

        return rootView;
    }

    private void onClickCopy(String text){
        try{
            ClipData myClip = ClipData.newPlainText("text", text);
            myClipboard.setPrimaryClip(myClip);
            Toast.makeText(CustomApplication.mContext, "内容已复制~",
                    Toast.LENGTH_SHORT).show();
        }catch (Exception e){

        }
    }

    //加载更多
    private void loadMore(){
        final Map<String,String> map = new HashMap<String, String>();
        map.put("type",type+"");
        map.put("pageIndex",pageindex+"");
        map.put("pageRecord",Records+"");
        map.put("uid",CommonUtils.formatString(userid));
        if (CommonUtils.isLogin() == true){
            map.put("token",CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        String url = "miniapp/"+"langappid"+"/getcomments.do";
        HttpsUtils.miniAppDo(map, url,  new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                //listview.stopLoadMore();
                mRefreshLayout.finishLoadMore();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    pageindex += 1;
                    List<DryCommentModel> l = GsonTools.getDryCommentModel1(data);
                    if (l != null && l.size() > 0){
                        if (l.size() >= Records){
                            //listview.setPullLoadEnable(true);
                            mRefreshLayout.setEnableLoadMore(true);
                        }else {
                            //listview.setPullLoadEnable(false);
                            mRefreshLayout.setEnableLoadMore(false);
                        }
                        list.addAll(l);
                    }else {
                        //listview.setPullLoadEnable(false);
                        mRefreshLayout.setEnableLoadMore(false);
                    }
                    adapter.notifyDataSetChanged();
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                //listview.stopLoadMore();
                mRefreshLayout.finishLoadMore();
            }
        });
    }

    public void getData(){
        pageindex = 0;
        if (listview == null){
            return;
        }
        if (list == null){
            list = new ArrayList<DryCommentModel>();
        }
        if (isNeedLogin == true){
            if (CommonUtils.isLogin() == false){
                //listview.stopRefresh(true);
                mRefreshLayout.finishRefresh();
                if (list.size() == 0){
                    login_button.setVisibility(View.VISIBLE);
                    no_data_img.setVisibility(View.INVISIBLE);
                }
                return;
            }
        }
        if (type == 1){
            if (CommonUtils.isLogin() == true){
                if (list.size() == 0){
                    login_button.setVisibility(View.INVISIBLE);
                    no_data_img.setVisibility(View.VISIBLE);
                }
            }else {
                login_button.setVisibility(View.VISIBLE);
                no_data_img.setVisibility(View.INVISIBLE);
            }
        }else {
            if (list.size() == 0){
                login_button.setVisibility(View.INVISIBLE);
                no_data_img.setVisibility(View.VISIBLE);
            }
        }
        new Thread(){
            @Override
            public void run() {
                super.run();
                //从缓存加载
                if (type == 2){//推荐轮播
                    if (pageindex == 0){
                        updateBanner();
                    }
                }
                if (list.size() == 0 && pageindex == 0){
                    String d = null;
                    if (type == 2){
                        d = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.HotCommentData,"");
                    }else if (type == 3){
                        d = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.LatestCommentData,"");
                    }else if (type == 4){
                        d = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.BestComment,"");
                    }
                    if (!CommonUtils.isEmpty(d)){
                        final List<DryCommentModel> l = GsonTools.getDryCommentModel1(d);
                        if (getActivity() == null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (l != null && l.size() > 0){
                                    login_button.setVisibility(View.INVISIBLE);
                                    no_data_img.setVisibility(View.INVISIBLE);
                                    list.addAll(l);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        });
                    }
                }

                final Map<String,String> map = new HashMap<String, String>();
                map.put("type",type+"");
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                map.put("uid",CommonUtils.formatString(userid));
                if (CommonUtils.isLogin() == true){
                    map.put("token",CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                }
                String url = "miniapp/"+"langappid"+"/getcomments.do";
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        Log.e("TAG","评论内容："+data);
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<DryCommentModel> l = GsonTools.getDryCommentModel1(data);
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //listview.stopRefresh(true);
                                    mRefreshLayout.finishRefresh();
                                    list.clear();
                                    if (l != null && l.size() > 0){
                                        if (pageindex == 0){
                                            if (type == 2){
                                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.HotCommentData,data);
                                            }else if (type == 3){
                                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.LatestCommentData,data);
                                            }else if (type == 4){
                                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.BestComment,data);
                                            }
                                        }
                                        login_button.setVisibility(View.INVISIBLE);
                                        no_data_img.setVisibility(View.INVISIBLE);
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        list.addAll(l);
                                        pageindex += 1;
                                    }else {
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    adapter.notifyDataSetChanged();
                                }
                            });
                        }else {
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //listview.stopRefresh(true);
                                    mRefreshLayout.finishRefresh();
                                    CustomApplication.showTip(commonModel, getActivity());
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        if (getActivity() == null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //listview.stopRefresh(true);
                                mRefreshLayout.finishRefresh();
                            }
                        });
                    }
                });
            }
        }.start();
    }

    private class MyAdapter extends BaseAdapter implements CommonItemViewController.EventDispatcher {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            if(type == 2){//推荐评论
                return list.size()+1;
            }
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            if (type == 2){//推荐评论
                return list.get(position-1);
            }
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        @Override
        public int getViewTypeCount() {
            if (type == 2){//推荐评论
                return 2;
            }
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            if (type == 2){//推荐评论
                if (position == 0){
                    return 0;
                }
                return 1;
            }else {
                return 1;
            }
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            View view = null;
            int itype = getItemViewType(position);
            if (itype == 0){
                //推荐评论类型布局
                if (convertView == null){
                    view = View.inflate(getActivity(), R.layout.banner_item_layout,null);
                }else {
                    view = convertView;
                }
                bannerView = (BannerView) view.findViewById(R.id.banner);
                bannerView.startLoop(true);
                ViewGroup.LayoutParams params = bannerView.getLayoutParams();
                params.width =screenWidth;
                params.height = screenWidth/2;
                bannerView.setLayoutParams(params);
                if (viewList != null && viewList.size() > 0){
                    bannerView.setViewList(viewList);
                }
                return view;
            }
            if (type == 2){
                //推荐评论
                position-=1;
            }
            CommonItemViewController controller = null;
            if (convertView != null) {
                controller = (CommonItemViewController) convertView.getTag(R.layout.drycomment_listview_item);
            }
            if (controller == null) {
                controller = new CommonItemViewController(getActivity(), R.layout.drycomment_listview_item, parent);
                controller.getBinding().getRoot().setTag(R.layout.drycomment_listview_item, controller);
            }

            DryCommentModel model = list.get(position);
            controller.setModel(model, position, MyAdapter.this);
            controller.getBinding().drycommentListviewItemReply.setVisibility(View.GONE);

            return controller.getBinding().getRoot();
        }

        @Override
        public void onComment(Integer index) {
            commentUser(index);
        }

        @Override
        public void onMoreAction(Integer index) {
            commentMore(index);
        }

        @Override
        public void onReplay(Integer index) {
            commentReply(index);
        }

        @Override
        public void onActionLike(Integer index) {
            commentLike(index);
        }

        @Override
        public void onActionCollect(Integer index) {
            commentCollect(index);
        }
    }

    //进入微句详情
    private void dealWithLang(String langid){
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, langid);
        if (CommonUtils.isLogin() == true){
            map.put("token",CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        String url = "miniapp/langappid/getlanginfo.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    LangInfoModel langInfoModel = GsonTools.getLangInfoModel(data);

                    if (langInfoModel.getStatus() == 1){
                        Intent intent = new Intent(getActivity(), LangDetailActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", langInfoModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                    }
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    //进入评论详情
    private void dealWithComment(String commentid, final String langid){
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, commentid);
        if (CommonUtils.isLogin() == true){
            map.put("token",CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        String url = "miniapp/langappid/commentcontent.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    DryCommentModel model = GsonTools.getCommentModel(data);
                    Intent intent = new Intent(getActivity(),LangCommentActivity.class);
                    intent.putExtra("id",langid);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("DryCommentModel", model);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    //点击了评论用户
    private void commentUser(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        final DryCommentModel model = list.get(index);
        //进入个人主页
        Intent intent = new Intent(getActivity(), UserLangActivity.class);
        intent.putExtra(APIKey.useridKey,model.getUserid());
        intent.putExtra(APIKey.typeKey,1);
        intent.putExtra(APIKey.titleKey,model.getNickname());
        startActivity(intent);
    }

    //评论点击更多
    private void commentMore(final int index){
        if (list == null || list.size() == 0 || index < 0){
            return;
        }
        final DryCommentModel model = list.get(index);
        moreList.clear();
        //moreList.add("分享");
        moreList.add("回复");
        if (model.getIslike().equals("0")){
            moreList.add("笔芯");
        }
        if (model.getIscollect().equals("0")){
            moreList.add("收藏");
        }
        moreList.add("复制");
        if (CommonUtils.isLogin() == true){
            if (CustomApplication.loginModel.getUid().equals(model.getUserid())){
                moreList.add("删除");
            }
        }
        moreList.add("来源微句");

        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(getActivity())
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : moreList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        String title = moreList.get(which-1);
                        if (title.equals("分享")){
                            commentShare(index);
                        }else if (title.equals("回复")){
                            commentReply(index);
                        }else if (title.equals("笔芯")){
                            commentLike(index);
                        }else if (title.equals("收藏")){
                            commentCollect(index);
                        }else if (title.equals("删除")){
                            CustomDialog dialog = null;
                            final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
                            builder.setTitle("温馨提示");
                            builder.setMessage("确定要删除？");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    commentDelete(index);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            dialog = builder.create();
                            dialog.show();
                        }else if (title.equals("来源微句")){
                            dealWithLang(model.getSourceid());
                        }else if (title.equals("复制")){
                            onClickCopy(model.getContent());
                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    //评论笔芯
    private void commentLike(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(getActivity(),LoginActivity.class);
            startActivity(intent);
            return;
        }
        final DryCommentModel model = list.get(index);
        if(CommonUtils.isEmpty(model.getCommentid())){
            return;
        }
        if (model.getIslike().equals("1")){
            return;
        }
        int count = Integer.valueOf(model.getLcount());
        count += 1;
        model.setLcount(count+"");
        model.setIslike("1");
        list.set(index,model);
        if (getActivity() == null){
            return;
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });

        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        map.put(APIKey.idKey,model.getCommentid());
        String url = "miniapp/"+"langappid"+"/langlikecomment.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
            }

            @Override
            public void onError(String msg) {
            }
        });
    }

    //评论收藏
    private void commentCollect(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(getActivity(),LoginActivity.class);
            startActivity(intent);
            return;
        }
        final DryCommentModel model = list.get(index);
        if(CommonUtils.isEmpty(model.getCommentid())){
            return;
        }
        if (model.getIscollect().equals("1")){
            return;
        }
        if (getActivity() == null){
            return;
        }
        model.setIscollect("1");
        model.setCollectcount(Integer.valueOf(model.getCollectcount())+1+"");
        adapter.notifyDataSetChanged();


        final HashMap<String, String> map = new HashMap<String, String>();
        if (CommonUtils.isLogin() == true){
            map.put("token",CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        map.put("sourceid", model.getCommentid());
        map.put(APIKey.typeKey,"0");
        String url = "miniapp/"+"langappid"+"/addcollection.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","收藏结果："+data);
            }

            @Override
            public void onError(String msg) {
            }
        });
    }

    //评论删除
    private void commentDelete(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(getActivity(),LoginActivity.class);
            startActivity(intent);
            return;
        }
        final DryCommentModel model = list.get(index);
        if(CommonUtils.isEmpty(model.getCommentid())){
            return;
        }
        final HashMap<String, String> map = new HashMap<String, String>();
        if (CommonUtils.isLogin() == true){
            map.put("token",CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        map.put("id", model.getCommentid());
        map.put(APIKey.typeKey,"0");
        String url = "miniapp/"+"langappid"+"/deletecomment.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","删除结果："+data);
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    list.remove(model);
                    adapter.notifyDataSetChanged();
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }

    //评论分享：进入评论详情
    private void commentShare(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        final DryCommentModel model = list.get(index);
        if (!CommonUtils.isEmpty(model.getCommentid())){
            Intent intent = new Intent(getActivity(),LangCommentActivity.class);
            intent.putExtra("id",model.getSourceid());
            Bundle bundle = new Bundle();
            bundle.putSerializable("DryCommentModel", model);
            intent.putExtras(bundle);
            intent.putExtra("isShare",true);
            startActivity(intent);
        }
    }

    //评论回复
    private void commentReply(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        DryCommentModel model = list.get(index);
        if (!CommonUtils.isEmpty(model.getCommentid())){
            Intent intent = new Intent(getActivity(),LangCommentActivity.class);
            intent.putExtra("id",model.getSourceid());
            Bundle bundle = new Bundle();
            bundle.putSerializable("DryCommentModel", model);
            intent.putExtras(bundle);
            intent.putExtra("isReply",true);
            startActivity(intent);
        }
    }

    /***************************轮播相关***************************/
    private void updateBanner(){
        //首次从缓存里面获取数据
        Log.e("TAG","首次从缓存里面获取数据Banner");
        if (bannerList == null){
            bannerList = new ArrayList<>();
        }
        if (bannerList.size() == 0){
            String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.CommentBannerData,"");
            if (!CommonUtils.isEmpty(data)){
                List<BannerModel> l = GsonTools.getBannerModel(data);
                if (l != null && l.size() > 0){
                    bannerList.addAll(l);
                }else {
                    BannerModel model = new BannerModel();
                    Byte type = 0;
                    model.setType(type);
                    model.setSourceid("");
                    model.setContent("对自己好点，因为一辈子不长；对身边的人好点，因为下辈子不一定能够遇见！");
                    model.setImg("http://image.daydayrise.net/wordbg181012.png");
                    model.setFontcolor("000000");
                    model.setFontname("");
                    model.setFontsize(18.0f);
                    bannerList.add(model);
                }
                String tdata = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.ThirdDataName,"");
                if (!CommonUtils.isEmpty(tdata)){
                    List<ThirdDataNameModel> ll = GsonTools.getThirdDataNameModel(tdata);
                    if (ll != null && ll.size() > 0){
                        for (ThirdDataNameModel m : ll){
                            BannerModel model = new BannerModel();
                            Byte type = -100;
                            model.setType(type);
                            model.setTypeid(m.getId());
                            model.setName(m.getName());
                            model.setImg(m.getBgurl());
                            model.setFontcolor("000000");
                            model.setFontname("");
                            model.setFontsize(18.0f);
                            bannerList.add(0,model);
                        }
                    }
                }
                upateBannerUI();
            }else {
                BannerModel model = new BannerModel();
                Byte type = 0;
                model.setType(type);
                model.setSourceid("");
                model.setContent("对自己好点，因为一辈子不长；对身边的人好点，因为下辈子不一定能够遇见！");
                model.setImg("http://image.daydayrise.net/wordbg181012.png");
                model.setFontcolor("000000");
                model.setFontname("");
                model.setFontsize(18.0f);
                bannerList.add(model);
                String tdata = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.ThirdDataName,"");
                if (!CommonUtils.isEmpty(tdata)){
                    List<ThirdDataNameModel> ll = GsonTools.getThirdDataNameModel(tdata);
                    if (ll != null && ll.size() > 0){
                        for (ThirdDataNameModel m : ll){
                            model = new BannerModel();
                            type = -100;
                            model.setType(type);
                            model.setTypeid(m.getId());
                            model.setName(m.getName());
                            model.setImg(m.getBgurl());
                            model.setFontcolor("000000");
                            model.setFontname("");
                            model.setFontsize(18.0f);
                            bannerList.add(0,model);
                        }
                    }
                }
                upateBannerUI();
            }
        }

        final HashMap<String, String> map = new HashMap<String, String>();
        if (CommonUtils.isLogin() == true){
            map.put("token",CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        map.put("type","1");
        String url = "miniapp/"+"langappid"+"/getbanner.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","轮播数据："+data);
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    List<BannerModel> l = GsonTools.getBannerModel(data);
                    if (l != null && l.size() > 0){
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.CommentBannerData,data);
                        bannerList.clear();
                        bannerList.addAll(l);
                        String tdata = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.ThirdDataName,"");
                        if (!CommonUtils.isEmpty(tdata)){
                            List<ThirdDataNameModel> ll = GsonTools.getThirdDataNameModel(tdata);
                            if (ll != null && ll.size() > 0){
                                for (ThirdDataNameModel m : ll){
                                    BannerModel model = new BannerModel();
                                    Byte type = -100;
                                    model.setType(type);
                                    model.setTypeid(m.getId());
                                    model.setName(m.getName());
                                    model.setImg(m.getBgurl());
                                    model.setFontcolor("000000");
                                    model.setFontname("");
                                    model.setFontsize(18.0f);
                                    bannerList.add(0,model);
                                }
                            }
                        }
                        upateBannerUI();
                    }
                }
            }

            @Override
            public void onError(String msg) {
                Log.e("TAG","轮播数据失败："+msg);
            }
        });

    }

    private void upateBannerUI(){
        if (getActivity() == null){
            return;
        }
        if (viewList == null){
            viewList = new ArrayList<View>();
        }
        if (bannerView == null){
            return;
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                viewList.clear();
                for (int i = 0; i < bannerList.size(); i++) {

                    BannerModel model = bannerList.get(i);
                    RelativeLayout layout = new RelativeLayout(getActivity());
                    layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    layout.setBackgroundColor(Color.parseColor("#ffffff"));

                    ImageView image = new ImageView(getActivity());
                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    //设置显示格式
                    image.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    image.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
                    if (CommonUtils.isEmpty(model.getImg())){
                        Glide.with(getActivity()).load("http://image.daydayrise.net/wordbg181012.png").placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(image);
                    }else {
                        Glide.with(getActivity()).load(model.getImg()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(image);
                    }
                    layout.addView(image);

                    if (model.getType() == 0 || model.getType() == 2){
                        final TextView textView = new TextView(getActivity());
                        ViewGroup.LayoutParams l = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                        textView.setLayoutParams(l);
                        textView.setTag(i);
                        if(model.getFontsize() == null){
                            textView.setTextSize(16);
                        }else {
                            textView.setTextSize(model.getFontsize()-2);
                        }
                        textView.setText(CommonUtils.formatString(model.getContent()));
                        textView.setGravity(Gravity.CENTER);
                        if (CommonUtils.isEmpty(model.getFontcolor())){
                            textView.setTextColor(Color.parseColor("#000000"));
                        }else {
                            textView.setTextColor(Color.parseColor("#"+model.getFontcolor()));
                        }
                        textView.setBackgroundColor(Color.parseColor("#00000000"));
                        textView.setPadding((int)(22),(int)(45),(int)(22),(int)(45));
                        textView.setLineSpacing(10,1);
                        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC));//加粗斜体
                        textView.getPaint().setFakeBoldText(true);//加粗
                        layout.addView(textView);
                    }

                    layout.setTag(i);
                    layout.setClickable(true);
                    layout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.e("TAG","点击："+v.getTag());
                            onClickBanner((int)v.getTag());
                        }
                    });
                    viewList.add(layout);
                }
                bannerView.setViewList(viewList);
            }
        });
    }

    //处理点击事件
    private void onClickBanner(final int index){
        if (bannerList != null && bannerList.size() > index){
            BannerModel model = bannerList.get(index);
            if (model.getType() == 2){
                //评论
                if(!CommonUtils.isEmpty(model.getSourceid())){
                    dealWithComment(model.getSourceid());
                }
            }else if (model.getType() == 1){
                //链接
                if (!CommonUtils.isEmpty(model.getContent())){
                    Intent webIntent = new Intent(getActivity(), MyWebActivity.class);
                    webIntent.putExtra(APIKey.urlKey, model.getContent());
                    startActivity(webIntent);
                }
            }else if (model.getType() == 4){
                //微句类型
                if (!CommonUtils.isEmpty(model.getSourceid())){
                    dealWithLang(model.getSourceid());
                }
            }else if (model.getType() == -100){
                //专题内容
                Intent intent = new Intent(getActivity(), ThirdLangActivity.class);
                intent.putExtra(APIKey.typeKey,model.getTypeid());
                intent.putExtra(APIKey.nameKey,model.getName());
                startActivity(intent);
            }
        }
    }

    private void dealWithComment(String commentid){
        avi.show();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, commentid);
        if (CommonUtils.isLogin() == true){
            map.put("token",CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        String url = "miniapp/langappid/commentcontent.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                avi.hide();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    DryCommentModel model = GsonTools.getCommentModel(data);
                    Intent intent = new Intent(getActivity(),LangCommentActivity.class);
                    intent.putExtra("id",model.getSourceid());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("DryCommentModel", model);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else {
                    CustomApplication.showTip(commonModel, getActivity());
                }
            }

            @Override
            public void onError(String msg) {
                avi.hide();
            }
        });
    }
    /***************************轮播相关***************************/
}
